package com.estore.network;

import com.estore.model.Product;
import com.estore.service.ProductService;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

public class EStoreServer {
    private final ProductService productService = new ProductService();
    private static final int PORT = 8888;

    public static void main(String[] args) {
        new EStoreServer().startServer();
    }

    private void startServer() {
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("服务器已启动，监听端口：" + PORT);
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("接收到客户端连接：" + clientSocket.getInetAddress());
                handleClient(clientSocket);
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    private void handleClient(Socket clientSocket) {
        try (ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
             ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream())) {

            // 读取客户端请求
            String request = (String) ois.readObject();
            System.out.println("接收到客户端请求：" + request);

            // 处理请求并返回数据
            if ("GET_ALL_PRODUCTS".equals(request)) {
                List<Product> products = productService.getAllProducts();
                oos.writeObject(products);
                oos.flush();
                System.out.println("已向客户端返回商品列表，共" + products.size() + "件商品");
            } else {
                oos.writeObject("未知请求");
                oos.flush();
                System.out.println("客户端发送无效请求：" + request);
            }

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("处理客户端请求失败：" + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
                System.out.println("客户端连接已关闭");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}